<template>
    <div class="myContainer">
        <el-row class="myBorderBottom">
            <el-col :span="7" class="myTitleText myLineHeight_40px">
                {{title}}
            </el-col>
        </el-row>
        <el-row :gutter="10" class="myPaddingTop_10px">
            <el-col :span="24">
                <el-steps :space="300" :active="active" finish-status="success" align-center>
                    <el-step title="步骤 1" description="设置基础信息"></el-step>
                    <el-step title="步骤 2" description="设置任务单相关人员"></el-step>
                    <el-step title="步骤 3" description="设置执行范围"></el-step>
                </el-steps>
            </el-col>
        </el-row>

        <el-row v-show="active==0" class="myPaddingTop_10px">
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="3" class="myLeftMsg">
                    <span class="require myVA_M">*</span>
                    职能任务名称 :
                </el-col>
                <el-col :span="6">
                    <el-input placeholder="职能任务名称" v-model="plan_title" :readonly="readonly"></el-input>
                </el-col>
            </el-row>
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="3" class="myLeftMsg">
                    <span class="require myVA_M">*</span>
                    模板 :
                </el-col>
                <el-col :span="6">
                    <template>
                        <el-select v-model="template_id"
                                   clearable
                                   :disabled="readonly"
                                   placeholder="请选择模板">
                            <el-option
                                v-for="item in template"
                                :key="item.template_name"
                                :label="item.template_name"
                                :value="item.template_id">
                            </el-option>
                        </el-select>
                    </template>
                </el-col>
            </el-row>
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="3" class="myLeftMsg">
                    <span class="require myVA_M">*</span>
                    监察人 :
                </el-col>
                <el-col :span="6">
                    <el-input placeholder="监察人" v-model="plan_pop" :disabled="readonly" @focus="showRole"></el-input>
                </el-col>
            </el-row>
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="3" class="myLeftMsg">
                    <span class="require myVA_M">*</span>
                    检查项完成率 :
                </el-col>
                <el-col :span="6">
                    <el-input placeholder="检查项完成率" v-model="finish_rate" :readonly="readonly"></el-input>
                </el-col>
                <el-col :span="2" class="myLineHeight_40px">
                    %
                </el-col>
            </el-row>
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="3" class="myLeftMsg">
                    <span class="require myVA_M">*</span>
                    开始日期 :
                </el-col>
                <el-col :span="6">
                    <el-date-picker
                        v-model="first_date"
                        type="date"
                        :editable=false
                        :disabled="readonly"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="开始日期"
                        :picker-options="pickerOptions"
                    >
                    </el-date-picker>
                </el-col>
            </el-row>
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="3" class="myLeftMsg">
                    <span class="require myVA_M">*</span>
                    截止日期 :
                </el-col>
                <el-col :span="6">
                    <el-date-picker
                        v-model="end_date"
                        type="date"
                        :editable=false
                        :disabled="readonly"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="截止日期"
                        :picker-options="pickerOptions"
                    >
                    </el-date-picker>
                </el-col>
            </el-row>
            <el-row :gutter="10" class="myPaddingTop_10px">
                <el-col :span="6" :offset="3">
                    <el-button @click="onstep(1,'down')">下一步</el-button>
                </el-col>
            </el-row>
        </el-row>


        <el-row v-show="active==1" class="myPaddingTop_10px">
            <el-row v-for="(i,index) in itemLists">
                <el-row class="myBorderBottom myMarginBottom_10px">
                    <el-col :span="7" class="myTitleText">{{i.type_name}}</el-col>
                </el-row>
                <el-row :gutter="10" class="myMarginBottom_10px">
                    <el-col :span="3" class="myLeftMsg">
                        <span class="require myVA_M">*</span>
                        责任人 :
                    </el-col>
                    <el-col :span="6">
                        <el-input placeholder="责任人" v-model="i.chargerole_name" :disabled="readonly"
                                  @focus="showRole(index,'chargerole_name','chargerole_id')"></el-input>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="myMarginBottom_10px">
                    <el-col :span="3" class="myLeftMsg">
                        处理人 :
                    </el-col>
                    <el-col :span="6">
                        <el-input placeholder="处理人" v-model="i.dealrole_name" :disabled="readonly"
                                  @focus="showRole(index,'dealrole_name','dealrole_id')"></el-input>
                    </el-col>
                </el-row>
            </el-row>
            <el-row :gutter="10" class="myPaddingTop_10px">
                <el-col :span="6" :offset="3">
                    <el-button @click="onstep(2,'up')">上一步</el-button>
                    <el-button @click="onstep(2,'down')">下一步</el-button>
                </el-col>
            </el-row>
        </el-row>

        <el-row v-show="active==2" class="myPaddingTop_10px">
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="6" class="myLineHeight_40px" :offset="3">
                    总项目数：{{totalNum}};
                    已选中：{{checkNum}};
                    占比：{{proportionNum}};
                </el-col>
            </el-row>
            <el-row :gutter="10" class="myMarginBottom_10px">
                <el-col :span="6" :offset="3">
                    <el-tree
                        :data="treeData"
                        show-checkbox
                        node-key="value"
                        ref="region"
                        :props="defaultProps"
                        @check-change="getAreaInfo"
                        :default-expanded-keys="[]"
                        :default-checked-keys="[]">
                    </el-tree>
                </el-col>
            </el-row>

            <el-row :gutter="10" class="myPaddingTop_10px">
                <el-col :span="6" :offset="3">
                    <el-button @click="onstep(3,'up')" :disabled="submitting">上一步</el-button>
                    <el-button type="primary" @click="onSub" :disabled="submitting">完成</el-button>
                </el-col>
            </el-row>
        </el-row>

        <el-dialog title="请选择角色/职务" class="myRoleDialog" :visible.sync="newRoleDialogVisible">
            <div>
                <el-input placeholder="输入关键字进行搜索" v-model="kw" class="input-with-select">
                    <el-button type="primary" slot="append" class="el-icon-search"></el-button>
                </el-input>
            </div>
            <div class="mymarginTop_10px myOV_y_400px">
                <el-tree
                    ref="roleData"
                    v-loading="roleDataListLoading"
                    :data="roleDataList"
                    node-key="role_id"
                    :props="RoleDataProps"
                    :filter-node-method="filterNode"
                    @check-change="onChange"
                    show-checkbox>
                </el-tree>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="myBgGreen" @click="setDeptRoleInfo">提 交</el-button>
                <el-button @click="newRoleDialogVisible = false">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<style scoped>
    .myBorderBottom {
        border-bottom: 1px dotted #dbdbdb;
        padding-bottom: 5px;
    }

    .myTextAlignRight {
        text-align: right;
    }

    .myContainer {
        background: #fff;
        padding: 10px;
    }

    .myTitleText {
        font-weight: 500;
        font-size: 16px;
    }

    .myLineHeight_40px {
        line-height: 40px;
    }

    .myPaddingTop_10px {
        padding-top: 10px;
    }

    .myred {
        color: #f00;
        font-size: 12px;
    }

    .myMarginBottom_10px {
        margin-bottom: 10px;
    }

    .myLeftMsg {
        line-height: 40px;
        text-align: right;
    }

    .myVA_M {
        vertical-align: middle;
    }

    .mymarginTop_10px {
        margin-top: 10px;
    }

    .myOV_y_400px {
        max-height: 400px;
        min-height: 200px;
        overflow-y: scroll;
        border: 1px solid #d1dbe5;
    }
</style>

<script>
    import {getAreaTree} from '@/api/area';
    import {addPlan, getTemplateList, infoPlan, updatePlan, createTask, infoTemplate} from '@/api/quality';
    import {getRoleList} from '@/api/role';

    export default {
        data() {
            return {
                title: "新增职能任务",
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 24 * 3600 * 1000;
                    }
                },
                type: "",
                id: "",
                readonly: false,
                radio: 1,
                template_id: "",
                template: [],
                treeData: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                gen_type: "",
                task: [
                    {label: "周期性", value: 1},
                    {label: "临时性", value: 0}
                ],
                sliderValue: 0,
                totalNum: 0,
                checkNum: 0,
                proportionNum: 0,
                deadline: "",
                finish_rate: "",
                first_date: "",
                plan_cycle: "",
                plan_title: "",
                areaid: "",
                areaname: "",
                gen_type: "",
                iszq: true,
                newList: [],
                checked: false,
                default_first_date: "",
                disabled: false,
                newRoleDialogVisible: false,
                plan_pop: "",
                roleDataList: [],
                kw: "",
                roleDataListLoading: false,
                RoleDataProps: {
                    label: 'role_name'
                },
                plan_pop_id: "",
                activeName: 'first',
                typeSelected: '',
                type: [],
                list: [],
                loading: false,
                submitting: false,
                active: 0,
                itemLists: [],
                item: [],
                zd: '',
                ids: '',
                i: 0,
                end_date: ''
            }
        },
        components: {},
        created() {
            this.type = this.$route.query.type;
            this.id = this.$route.query.id;

            this.ongetTemplateList();
            if (this.type == "add") {
                document.title = "新增计划";
            } else if (this.type == "info") {
                this.readonly = true;
            } else if (this.type == "update") {
                document.title = "编辑计划";
                this.readonly = false;
                this.disabled = true;
            }
        },
        computed: {},
        watch: {
            kw(val) {
                this.$refs.roleData.filter(val);
            },
            template_id(val) {
                this.oninfoTemplate(val);
            }
        },
        methods: {
            filterNode(value, data) {
                if (!value) return true;
                return data.role_name.indexOf(value) !== -1;
            },
            add() {
                let vm = this;
                let params = {
                    "area_range": vm.areaid,
                    "deadline": Number(vm.deadline),
                    "finish_rate": Number(vm.finish_rate).toFixed(2),
                    "first_date": vm.first_date,
                    "gen_type": vm.gen_type,
                    "plan_cycle": Number(vm.plan_cycle),
                    "plan_title": vm.plan_title,
                    "template_id": vm.template_id
                }
                if (vm.checkNum <= 0) {
                    vm.$message.info("执行范围最少为一个小区！");
                    return;
                }
                if (vm.gen_type == 1 && (Number(vm.deadline) > Number(vm.plan_cycle))) {
                    vm.$message.info("选择周期性任务时期限不能超过周期！");
                    return;
                }
                if (vm.checked) {
                    vm.$confirm(`是否立即创建 [ ${vm.plan_title} ] 内的任务？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        addPlan(params).then(response => {
                            let res = response.data;
                            vm.$message.success("计划创建成功！");
                            if (res.data_id) {
                                createTask(res.data_id).then(response => {
                                    vm.$message.success("任务创建成功！");
                                    vm.back();
                                }).catch(error => {
                                    vm.$message.error("任务创建失败！" + error.response.data.error_msg);
                                })
                            }
                        }).catch(error => {
                            vm.$message.error("计划创建失败！" + error.response.data.error_msg);
                        })
                    }).catch(() => {
                    });
                } else {
                    addPlan(params).then(response => {
                        vm.$message.success("计划创建成功！");
                        vm.back();
                    }).catch(error => {
                        vm.$message.error("执行失败！" + error.response.data.error_msg);
                    })
                }
            },
            update() {
                let vm = this;
                let params = {
                    "area_range": vm.areaid,
                    "deadline": Number(vm.deadline),
                    "finish_rate": Number(vm.finish_rate).toFixed(2),
                    "first_date": vm.first_date,
                    "gen_type": vm.gen_type,
                    "plan_cycle": Number(vm.plan_cycle),
                    "plan_title": vm.plan_title,
                    "template_id": vm.template_id
                }
                if (vm.checkNum <= 0) {
                    vm.$message.info("执行范围最少为一个小区！");
                    return;
                }
                if (vm.gen_type == 1 && (Number(vm.deadline) > Number(vm.plan_cycle))) {
                    vm.$message.info("选择周期性任务时期限不能超过周期！");
                    return;
                }
                if (vm.checked) {
                    vm.$confirm(`是否立即创建 [ ${vm.plan_title} ] 内的任务？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        updatePlan(params, vm.id).then(response => {
                            vm.$message.success("计划修改成功！");
                            createTask(vm.id).then(response => {
                                vm.$message.success("任务创建成功！");
                                vm.back();
                            }).catch(error => {
                                vm.$message.error("任务创建失败！" + error.response.data.error_msg);
                            })
                        }).catch(error => {
                            vm.$message.error("计划修改失败！" + error.response.data.error_msg);
                        })
                    }).catch(() => {
                    });
                } else {
                    updatePlan(params, vm.id).then(response => {
                        vm.$message.success("计划修改成功！");
                        vm.back();
                    }).catch(error => {
                        vm.$message.error("计划修改失败！" + error.response.data.error_msg);
                    })
                }
            },
            back() {
                this.$router.go(-1);
            },
            ongetTemplateList() {
                let vm = this;
                let params = {
                    type: 1,
                    page_num: 1,
                    page_size: 10000
                }
                getTemplateList(params).then(response => {
                    let res = response.data;
                    if (!res.rows.length) return;
                    vm.template = [];
                    res.rows.forEach(item => {
                        if (item.template_type == 1) {
                            vm.template.push(item);
                        }
                    })
                    // vm.template=res.rows;
                }).catch(error => {
                    vm.$message.error("执行失败！" + error.response.data.error_msg);
                })
            },
            getAreaInfo() {
                let vm = this;
                let areas = vm.$refs.region.getCheckedNodes();
                let areaids = "", areanames = "", num = 0;
                for (let i = 0; i < areas.length; i++) {
                    if (areas[i].level == 3) {
                        areaids += areas[i].value + ',';
                        areanames += areas[i].label + ',';
                        num++;
                    }
                }
                vm.areaname = areanames.substring(0, areanames.length - 1);
                vm.areaid = areaids.substring(0, areaids.length - 1);
                vm.checkNum = num;
                vm.proportionNum = ((num / vm.totalNum) * 100).toFixed(2) + '%';
            },
            ongetAreaTree() {
                let vm = this;
                getAreaTree().then(response => {
                    let res = response.data;
                    let num = 0;
                    vm.treeData = res;
                    for (let i = 0; i < res.length; i++) {
                        vm.onGetArr(res[i]);
                    }
                    for (let i = 0; i < vm.newList.length; i++) {
                        if (vm.newList[i].level == 3) {
                            num++;
                        }
                    }
                    vm.totalNum = num;
                    if (vm.type == 'info' || vm.type == 'update') {
                        vm.info();
                    }
                }).catch(error => {
                    vm.$message.error("执行失败！" + error.response.data.error_msg);
                })
            },
            onGetArr(e) {
                let vm = this;
                vm.newList.push(e);
                if (e.children) {
                    for (let i = 0; i < e.children.length; i++) {
                        vm.onGetArr(e.children[i]);
                    }
                }
            },
            info() {
                let vm = this;
                infoPlan(vm.id).then(response => {
                    let res = response.data;
                    vm.areaid = res.area_range;
                    vm.$refs.region.setCheckedKeys(res.area_range.split(','));
                    vm.deadline = res.deadline;
                    vm.finish_rate = res.finish_rate;
                    vm.first_date = res.first_date;
                    vm.default_first_date = res.first_date;
                    vm.gen_type = res.gen_type;
                    vm.plan_cycle = res.plan_cycle;
                    vm.plan_title = res.plan_title;
                    vm.template_id = res.template_id;
                }).catch(error => {
                    vm.$message.error("执行失败！" + error.response.data.error_msg);
                })
            },
            checkedChange(val) {
                if (val) {
                    this.first_date = new Date();
                } else {
                    this.first_date = this.default_first_date;
                }
            },
            changeType(val) {
                if (val == 1) {
                    this.checked = false;
                }
            },
            showRole(item, zd, ids) {
                this.i = 0;
                this.item = item;
                this.zd = zd;
                this.ids = ids;
                this.roleDataList = [];
                this.newRoleDialogVisible = true;
                this.kw = '';
                this.getRoleList();
            },
            getRoleList() {
                let vm = this;
                let params = {
                    page_num: 1,
                    page_size: 1000
                };
                vm.roleDataListLoading = true;
                getRoleList(params)
                    .then(response => {
                        let res = response.data;
                        vm.roleDataList = res.rows;
                        vm.$refs.roleData.setCheckedKeys([]);
                        vm.roleDataListLoading = false;
                    })
                    .catch(error => {
                        vm.roleDataListLoading = false;
                    })
            },
            onChange(a, b, c) {
                let vm = this;
                vm.i++;
                if (vm.i % 2 == 0) {
                    if (b) {
                        vm.$refs.roleData.setCheckedKeys([]);
                        vm.$refs.roleData.setCheckedKeys([a.role_id]);
                    } else {
                        vm.$refs.roleData.setCheckedKeys([]);
                    }
                }
            },
            setDeptRoleInfo() {
                let checkNode = this.$refs.roleData.getCheckedNodes();
                let roleid = new Array(checkNode.length);
                let rolename = new Array(checkNode.length);
                for (let i = 0; i < checkNode.length; i++) {
                    roleid[i] = checkNode[i].role_id;
                    rolename[i] = checkNode[i].role_name;
                }
                if (this.active == 0) {
                    this.plan_pop = rolename.join(',');
                    this.plan_pop_id = roleid.join(',');
                } else if (this.active == 1) {
                    this.itemLists[this.item][this.zd] = rolename.join(',');
                    this.itemLists[this.item][this.ids] = roleid.join(',');
                }
                this.newRoleDialogVisible = false;
            },
            handleClick(a, b) {

            },
            goinfo() {
                this.$router.push({
                    path: "tasklistMGTComonentsDetail",
                    query: {
                        type: "info",
                        id: ''
                    }
                })
            },
            search() {

            },
            oninfoTemplate(id) {
                let vm = this;
                infoTemplate(id).then(response => {
                    let res = response.data;
                    vm.itemLists = res.type_st;
                }).catch(error => {
                    vm.$message.error("执行失败！" + error.response.data.error_msg);
                })
            },
            onstep(step, fangxiang) {
                let vm = this;
                if (step == 1 && fangxiang == 'down') {//第一步向下
                    if (!vm.plan_title || !vm.template_id || !vm.plan_pop || !vm.finish_rate || !vm.first_date || !vm.end_date) {
                        vm.$message.info("必要数据请填写完整！");
                        return;
                    }
                    vm.active++;
                } else if (step == 2 && fangxiang == 'up') {//第二步向上
                    vm.active--;
                } else if (step == 2 && fangxiang == 'down') {//第二步向下
                    for (let i = 0; i < vm.itemLists.length; i++) {
                        if (!vm.itemLists[i].chargerole_name) {//!vm.itemLists[i].dealrole_name ||
                            vm.$message.info("必要数据请填写完整！");
                            return;
                        }
                    }
                    vm.active++;
                    vm.ongetAreaTree();
                } else if (step == 3 && fangxiang == 'up') {//第三步向上
                    vm.active--;
                }
            },
            onSub() {
                let vm = this;
                vm.submitting=true;

                let st_typename = [];
                let st_type = [];

                let dealrole_name = [];
                let dealrole_id = [];

                let chargerole_name = [];
                let chargerole_id = [];

                if (!vm.checkNum) {
                    vm.$message.info("必要数据请填写完整！");
                    return;
                }
                for (let i = 0; i < vm.itemLists.length; i++) {

                    st_typename.push(vm.itemLists[i].type_name);
                    st_type.push(vm.itemLists[i].type_id);

                    //如果处理人为空，角色id 设定为-1
                    dealrole_name.push(vm.itemLists[i].dealrole_name || '未设定');
                    dealrole_id.push(vm.itemLists[i].dealrole_id || '-1');

                    chargerole_name.push(vm.itemLists[i].chargerole_name);
                    chargerole_id.push(vm.itemLists[i].chargerole_id);

                }
                let params = {
                    "area_range": vm.areaid,
                    // "deadline": Number(vm.deadline),
                    "finish_rate": Number(vm.finish_rate).toFixed(2),
                    "start_time": vm.first_date,
                    "end_time": vm.end_date,
                    "gen_type": 0,
                    // "plan_cycle": Number(vm.plan_cycle),
                    "plan_title": vm.plan_title,
                    "template_id": vm.template_id,
                    "supervisorrole_name": vm.plan_pop,
                    "supervisorrole_id": vm.plan_pop_id,
                    "st_typename": st_typename.join(","),
                    "st_type": st_type.join(","),
                    "dealrole_name": dealrole_name.join(","),
                    "dealrole_id": dealrole_id.join(","),
                    "chargerole_name": chargerole_name.join(","),
                    "chargerole_id": chargerole_id.join(","),
                }
                addPlan(params).then(response => {
                    vm.$message.success("创建成功！");
                    vm.back();
                    vm.submitting=false;
                }).catch(error => {
                    vm.$message.error("执行失败！" + error.response.data.error_msg);
                    vm.submitting=false;
                })
            }
        }
    }
</script>

